<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
                <template v-if="mode === 'edit'">
                    <el-form-item label="海报" prop="img">
                        <el-input v-model="formData.img" placeholder="请输入海报URL" clearable />
                    </el-form-item>

                    <el-form-item label="标题" prop="title">
                        <el-input v-model="formData.title" placeholder="请输入标题" clearable />
                    </el-form-item>
                </template>
                <template v-else>
                    <el-form-item label="海报" prop="img">
                        <el-input v-model="formData.img" placeholder="请输入海报URL" clearable />
                    </el-form-item>

                    <el-form-item label="标题" prop="title">
                        <el-input v-model="formData.title" placeholder="请输入标题" clearable />
                    </el-form-item>
                </template>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus";

import Popup from "@/components/popup/index.vue";
import { addListAPI, getListOneAPI, updateListOneAPI } from "@/api/list";


const emit = defineEmits(["success", "close"]);

const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();

const mode = ref("add");

const popupTitle = computed(() => {
    return mode.value == "edit" ? "编辑用户信息" : "新增用户信息";
});
const formData = reactive({
    id: "",
    img: "",
    title: ""
});

const formRules = reactive<FormRules>({
    img: [
        {
            required: true,
            message: "请输入海报URL",
            trigger: ["blur"]
        }
    ],
    title: [
        {
            required: true,
            message: "请输入电影标题",
            trigger: ["blur"]
        }
    ]
});

const handleSubmit = async () => {
    await formRef.value?.validate();
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { id, ...rest } = formData;
    mode.value == "edit" ? await updateListOneAPI(formData as any) : await addListAPI({ ...rest } as any);
    popupRef.value?.close();
    emit("success");
};

const open = (type = "add") => {
    mode.value = type;
    popupRef.value?.open();
};

// 编辑管理员，数据回显
const setFormData = async (row: any) => {
    const data = await getListOneAPI(row.id);
    // 数据回显
    safeFormMerge(formData, data);
};

// 类型安全的深度合并函数
function safeFormMerge<T extends Record<string, any>>(formData: T, serverData: Record<string, any>): T {
    Object.keys(formData).forEach(key => {
        const formVal = formData[key];
        const serverVal = serverData[key];

        if (typeof serverVal === "undefined") return; // 忽略服务端不存在的字段

        // 深度合并对象
        if (isPlainObject(formVal) && isPlainObject(serverVal)) {
            safeFormMerge(formVal, serverVal);
        }
        // 数组替换
        else if (Array.isArray(formVal) && Array.isArray(serverVal)) {
            formData[key as keyof T] = serverVal.slice() as any;
        }
        // 基础类型直接赋值
        else {
            formData[key as keyof T] = serverVal;
        }
    });
    return formData;
}

// 判断是否为普通对象
function isPlainObject(v: any): v is Record<string, any> {
    return v?.constructor === Object;
}

const handleClose = () => {
    emit("close");
};

defineExpose({
    open,
    setFormData
});
</script>
